package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.SociaUser;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.excepiton.PhoneExistException;
import com.atguigu.gulimall.member.excepiton.UserNameExistException;
import com.atguigu.gulimall.member.vo.MemberRegisVo;
import com.atguigu.gulimall.member.vo.UserLoginVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegisVo vo) {
        MemberDao baseMapper = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        //1、设置默认等级(查出哪个等级是默认等级，在设值)
        Long default_level = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1)).getId();
        entity.setLevelId(default_level);
        //2、检查用户名和手机号是否唯一。主动抛出异常，让controller感知到
        checkUserNameUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());

        entity.setUsername(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setNickname(vo.getUserName());
        //密码需要加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他默认信息
        baseMapper.insert(entity);
    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        Integer userName1 = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("userName", userName));
        if (userName1 > 0)
            throw new UserNameExistException();
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer phone1 = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (phone1 > 0)
            throw new PhoneExistException();
    }

    //用户登录
    @Override
    public MemberEntity login(UserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String prePassword = vo.getPassword();
        //1、先根据loginacct查询数据库（用户名或手机号）
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity != null) {
            //2、对比密码(明文和加密后的密码)
            String password1 = memberEntity.getPassword();
            boolean b = new BCryptPasswordEncoder().matches(prePassword, password1);
            if (b == true) {
                //密码正常
                return memberEntity;
            } else {
                //密码错误
                return null;
            }
        }
        return null;
    }

    //社交登录
    @Override
    public MemberEntity login(SociaUser sociaUser) throws Exception {
        //登录和注册合并逻辑
        String uid = sociaUser.getUid();
        //1、判断当前社交用户是否已经存在
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //已存在
            MemberEntity memberEntity1 = new MemberEntity();
            memberEntity1.setId(memberEntity.getId());
            memberEntity1.setAccessToken(sociaUser.getAccess_token());
            memberEntity1.setExpiresIn(sociaUser.getExpires_in());
            //更新 令牌、令牌过期时间
            this.baseMapper.updateById(memberEntity1);

            memberEntity.setAccessToken(sociaUser.getAccess_token());
            memberEntity.setExpiresIn(sociaUser.getExpires_in());
            return memberEntity;
        } else {
            //2、如果当前社交用户不存在，则注册
            MemberEntity regist = new MemberEntity();
            try {
                //3、查询当前社交用户的账号信息(昵称、性别等)
                Map<String, String> query = new HashMap<>();
                query.put("access_token", sociaUser.getAccess_token());
                query.put("uid", sociaUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
//                    String json = response.getEntity().toString();
                    JSONObject jsonObject = JSON.parseObject(json);
                    //当前社交账号：昵称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    //....·
                    if (name != null) {
                        regist.setNickname(name);
                    }else {
                        regist.setNickname("默认名字");
                    }
                    if (gender != null) {
                        regist.setGender("m".equals(gender) ? 0 : 1);
                    }else {
                        regist.setGender(0);
                    }
                }
            } catch (Exception ex) {
            }
            regist.setSocialUid(sociaUser.getUid());
            regist.setAccessToken(sociaUser.getAccess_token());
            regist.setExpiresIn(sociaUser.getExpires_in());
            //注册用户
            this.baseMapper.insert(regist);
            return regist;
        }
    }


}